package com.flnet.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.flnet.api.annotation.IgnoreAuth;
import com.flnet.api.domain.FullUserInfo;
import com.flnet.api.domain.Member;
import com.flnet.api.domain.UserInfo;
import com.flnet.api.service.IMemberService;
import com.flnet.api.service.ITbTokenService;
import com.flnet.api.util.ApiBaseAction;
import com.flnet.api.util.ApiUserUtils;
import com.flnet.api.util.CommonUtil;
import com.flnet.common.base.AjaxResult;
import com.flnet.common.utils.CharUtil;
import com.flnet.common.validator.Assert;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * API登录授权
 */
@Api(tags = "API登录授权接口")
@RestController
@RequestMapping("/api/auth")
public class ApiAuthController extends ApiBaseAction{

    @Autowired
    private ITbTokenService iTbTokenService;

    @Autowired
    private IMemberService iMemberService;

    /**
     * 登录
     */
    @IgnoreAuth
    @PostMapping("login")
    @ApiOperation(value = "登录接口")
    public AjaxResult login(String mobile, String password) {
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");
        //用户登录
        long userId = iMemberService.login(mobile,password);
        //生成token
        Map<String, Object> map = tokenService.createToken(userId);
        return AjaxResult.success(map);
    }

    /**
     * 登录
     */
    @ApiOperation(value = "登录")
    @IgnoreAuth
    @PostMapping("login_by_weixin")
    public Object loginByWeixin(){
        JSONObject jsonParam = this.getJsonRequest();
        FullUserInfo fullUserInfo = null;
        String code = "";
        if (!StringUtils.isNullOrEmpty(jsonParam.getString("code"))) {
            code = jsonParam.getString("code");
        }
        if (null != jsonParam.get("userInfo")) {
            fullUserInfo = jsonParam.getObject("userInfo", FullUserInfo.class);
        }
        if (null == fullUserInfo) {
            return toResponsFail("登录失败");
        }

        Map<String, Object> resultObj = new HashMap<String, Object>();
        //
        UserInfo userInfo = fullUserInfo.getUserInfo();

        //获取openid
        String requestUrl = ApiUserUtils.getWebAccess(code);//通过自定义工具类组合出小程序需要的登录凭证 code
        logger.info("》》》组合token为：" + requestUrl);
        JSONObject sessionData = CommonUtil.httpsRequest(requestUrl, "GET", null);

        if (null == sessionData || StringUtils.isNullOrEmpty(sessionData.getString("openid"))) {
            return toResponsFail("登录失败");
        }
        //验证用户信息完整性
        String sha1 = CommonUtil.getSha1(fullUserInfo.getRawData() + sessionData.getString("session_key"));
        if (!fullUserInfo.getSignature().equals(sha1)) {
            return toResponsFail("登录失败");
        }

        Date nowTime = new Date();
        Member member = iMemberService.queryByOpenId(sessionData.getString("openid"));
        if(null == member){
            member = new Member();
            member.setMemberName("微信用户" + CharUtil.getRandomString(12));
            member.setPassword(sessionData.getString("openid"));
            member.setRegister_time(nowTime);
            member.setRegister_ip(this.getClientIp());
            member.setLast_login_ip(member.getRegister_ip());
            member.setLast_login_time(member.getRegister_time());
            member.setOpenid(sessionData.getString("openid"));
            member.setAvatar(userInfo.getAvatarUrl());
            member.setSex(userInfo.getGender().toString()); // //性别 0：未知、1：男、2：女
            member.setNickname(userInfo.getNickName());
            iMemberService.insertWMember(member);
        } else {
            member.setLast_login_ip(this.getClientIp());
            member.setLast_login_time(nowTime);
            iMemberService.updateWMember(member);
        }

        Map<String, Object> tokenMap = tokenService.createToken(member.getMemberId());
        String token = MapUtils.getString(tokenMap, "token");

        if (null == userInfo || StringUtils.isNullOrEmpty(token)) {
            return toResponsFail("登录失败");
        }

        resultObj.put("token", token);
        resultObj.put("userInfo", userInfo);
        resultObj.put("userId", member.getMemberId());
        return toResponsSuccess(resultObj);
    }
}
